package com.yyx.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yyx.server.pojo.Admin;
import com.yyx.server.pojo.Menu;
import com.yyx.server.pojo.MenuRole;
import com.yyx.server.pojo.Role;
import com.yyx.server.service.MenuRoleService;
import com.yyx.server.service.MenuService;
import com.yyx.server.service.RoleService;
import com.yyx.server.vo.PermissionChildrenVo;
import com.yyx.server.vo.ResultVo;
import com.yyx.server.vo.ServicePermissionVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限组
 * @author YongXin
 * @date Created in 2021/8/7 13:45
 */
@RestController
@RequestMapping("/system/basic/permiss")
public class PermissController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private MenuRoleService menuRoleService;

    @ApiOperation("获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRoles(){
        return roleService.list();
    }
    @ApiOperation("添加角色")
    @PostMapping("/role")
    public ResultVo addRole(@RequestBody Role role){
        if (!role.getName().startsWith("ROLE_")){
            role.setName("ROLE_"+role.getName());
        }
        if (roleService.save(role)){
            return ResultVo.success("添加成功");
        }
        return ResultVo.error("添加失败");
    }
    @ApiOperation("删除角色")
    @DeleteMapping("/role/{rid}")
    public ResultVo delRole(@PathVariable Integer rid){
        if (roleService.removeById(rid)){
            return ResultVo.success("删除成功");
        }
        return ResultVo.error("删除失败");
    }
    @ApiOperation("查询所有菜单")
    @GetMapping("/menus")
    public List<Menu> getAllMenus(){
        return menuService.getAllMenus();
    }
    @ApiOperation("根据角色id查询菜单id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid){
        QueryWrapper<MenuRole> wrapper = new QueryWrapper<MenuRole>().eq("rid", rid);
        return menuRoleService.list(wrapper).stream().map(MenuRole::getMid).collect(Collectors.toList());
    }
    @ApiOperation("更新角色菜单")
    @PutMapping("/")
    public ResultVo updMenuRole(Integer rid,Integer[] mids){
       return menuRoleService.updMenuRole(rid,mids);
    }

    @ApiOperation("获取用户动态路由")
    @PutMapping("/servicePermissionMap")
    public ServicePermissionVo getServicePermissionMap(Authentication authentication){
        Admin admin = (Admin)authentication.getPrincipal();
        //拥有角色
        List<Role> roles = admin.getRoles();
        //拥有的所有权限
        ArrayList<Integer> menuAllList = new ArrayList<>();
        for (Role role : roles) {
            QueryWrapper<MenuRole> menuRoleWrapper = new QueryWrapper<MenuRole>().eq("rid", role.getId());
            List<Integer> menuList = menuRoleService.list(menuRoleWrapper).stream().map(MenuRole::getMid).collect(Collectors.toList());
            menuAllList.addAll(menuList);
        }
        //去重
        HashSet<Integer> allMenu = new HashSet<>(menuAllList);
        //权限集合
        ArrayList<PermissionChildrenVo> allPermisson = new ArrayList<>();
        for (Integer menuId : allMenu) {
            Menu menu = menuService.getById(menuId);
            if (menuService.getById(menu.getParentId()).getParentId() == 1){ //是二级菜单
                Menu menu1 = menuService.getById(menu.getParentId()); //该二级的父
                if(allPermisson.stream().filter(w->String.valueOf(w.getTitle()).equals(menu1.getName())).findAny().isPresent()){
                    String parName = menuService.getById(menu.getParentId()).getName();
                    for (PermissionChildrenVo childrenVo : allPermisson) {
                        if (childrenVo.getTitle().equals(parName)){
                            List<PermissionChildrenVo> childrenVos2 = childrenVo.getChildren();
                            //二级菜单
                            PermissionChildrenVo childrenVo2 = new PermissionChildrenVo();
                            childrenVo2.setTitle(menu.getName());
                            childrenVo2.setUrl(menu.getUrl());
                            childrenVo2.setComponent(menu.getComponent());
                            childrenVo2.setIcon(menu.getIconCls());
                            childrenVos2.add(childrenVo2);
                        }
                    }
                }else {
                    //一级菜单
                    PermissionChildrenVo childrenVo1 = new PermissionChildrenVo();
                    childrenVo1.setTitle(menu1.getName());
                    //数据库中并无key字段,前端用key来拼接url,而此库存在url字段
                    //permissionChildrenVo.setKey(menu.getKey());
                    //直接返回url，新建导航时后端进行拼接处理，前端不做处理
                    childrenVo1.setUrl(menu1.getUrl());
                    childrenVo1.setComponent(menu1.getComponent());
                    childrenVo1.setIcon(menu1.getIconCls());
                    //二级菜单
                    PermissionChildrenVo childrenVo2 = new PermissionChildrenVo();
                    childrenVo2.setTitle(menu.getName());
                    childrenVo2.setUrl(menu.getUrl());
                    childrenVo2.setComponent(menu.getComponent());
                    childrenVo2.setIcon(menu.getIconCls());
                    ArrayList<PermissionChildrenVo> childrenVos2 = new ArrayList<>();
                    childrenVos2.add(childrenVo2);
                    childrenVo1.setChildren(childrenVos2);
                    allPermisson.add(childrenVo1);
                }
            }
        }
        return new ServicePermissionVo("动态路由",allPermisson,200,"234325435436");
    }
}
